package cn.ibizlab.util.adapter.service.impl;

import cn.ibizlab.util.adapter.service.SysRuntimeAdapterService;
import cn.ibizlab.util.adapter.util.constant.DELogicConstant;
import cn.ibizlab.util.adapter.util.helper.CachedBeanCopier;
import cn.ibizlab.util.helper.StringAdvUtils;
import cn.ibizlab.util.security.SpringContextHolder;
import lombok.SneakyThrows;
import net.ibizsys.central.dataentity.demap.IDEMapRuntime;
import net.ibizsys.central.util.IEntityDTO;
import net.ibizsys.model.PSModelEnums;
import net.ibizsys.model.dataentity.action.IPSDEAction;
import net.ibizsys.model.dataentity.action.IPSDELogicAction;
import net.ibizsys.model.dataentity.action.IPSDEScriptAction;
import net.ibizsys.model.dataentity.defield.IPSDEField;
import net.ibizsys.model.dataentity.wf.IPSDEWF;
import net.ibizsys.runtime.DynaInstModes;
import net.ibizsys.runtime.IDynaInstRuntime;
import net.ibizsys.runtime.dataentity.DataEntityRuntimeException;
import net.ibizsys.runtime.dataentity.IDynaInstDataEntityRuntime;
import net.ibizsys.runtime.dataentity.action.*;
import net.ibizsys.runtime.dataentity.datasync.DEDataSyncEvents;
import net.ibizsys.runtime.util.*;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import java.util.List;
import static cn.ibizlab.util.adapter.util.constant.DELogicConstant.*;

/**
 * adapter 实体运行时对象：用于在 runtime 执行实体行为时将请求转发至业务端进行处理
 */
public class DefaultAdapterDataEntityRuntime extends DefaultAdapterDataEntityRuntimeBase {

    SysRuntimeAdapterService sysRuntimeAdapterService;
    private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(DefaultAdapterDataEntityRuntime.class);

    /**
     * 接管runtime实体行为调用逻辑，将runtime行为请求转发到业务端的实体行为进行处理
     * @param strActionName
     * @param iPSDEAction
     * @param args
     * @param actionData
     * @return
     * @throws Throwable
     */
    @Override
    protected Object onExecuteActionReal(String strActionName, IPSDEAction iPSDEAction, Object[] args, Object actionData) throws Throwable {

        //外部接口实体、自定义行为（操作类型为：创建/读取/更新数据等）、通过键值获取的行为类型、虚拟实体、处理逻辑均交由runtime处理
        if (DELogicConstant.DATAENTITY_STORAGEMODE_SERVICEAPI == this.getStorageMode()
                || (this.getPSDataEntity().getAllPSDEMaps() != null && this.getStorageMode() == DELogicConstant.DATAENTITY_STORAGEMODE_NONE)
                || (DEActionTypes.USERCUSTOM.equals(iPSDEAction.getActionType()) && !DELogicConstant.DATAENTITY_ACTIONMODE_CUSTOM.equalsIgnoreCase(iPSDEAction.getActionMode()))
                || (DEActionTypes.SELECTBYKEY.equals(iPSDEAction.getActionType()) && !DELogicConstant.DATAENTITY_ACTIONMODE_READ.equalsIgnoreCase(iPSDEAction.getActionMode()))
                || (DATAENTITY_STORAGEMODE_NONE == this.getStorageMode() && this.isVirtual() && DATAENTITY_VIRTUALMODE_INDEXMAJOR == this.getVirtualMode())
                || DEActionTypes.DELOGIC.equalsIgnoreCase(iPSDEAction.getActionType())){
                return super.onExecuteActionReal(strActionName, iPSDEAction, args, actionData);
        }

        return getSysRuntimeAdapterService().executeActionReal(this, iPSDEAction, args != null ? args[0]: null);
    }

    /**
     * 获取 adapter 服务对象
     *
     * @return
     */
    protected SysRuntimeAdapterService getSysRuntimeAdapterService() {

        if (sysRuntimeAdapterService == null) {
            sysRuntimeAdapterService = SpringContextHolder.getBean(SysRuntimeAdapterService.class);
        }
        return sysRuntimeAdapterService;
    }

    /**
     * 获取实体属性值（优先按原codeName取，取不到时按codeName驼峰值取）
     * @param objEntity
     * @param iPSDEField
     * @return
     */
    @Override
    public Object getFieldValue(IEntityBase objEntity, IPSDEField iPSDEField) {
        Object object =  super.getFieldValue(objEntity, iPSDEField);
        if(object == null)
            object = getEntity(objEntity).get(StringAdvUtils.camelcase(iPSDEField.getLowerCaseName()));
        return object;
    }

    @SneakyThrows
    @Override
    public int checkKeyState(Object objKey) {
        if(DELogicConstant.DATAENTITY_STORAGEMODE_SERVICEAPI == this.getStorageMode()
                || (this.getPSDataEntity().getAllPSDEMaps() != null && this.getStorageMode() == DELogicConstant.DATAENTITY_STORAGEMODE_NONE)
                ||DATAENTITY_STORAGEMODE_NONE == this.getStorageMode() && this.isVirtual() && DATAENTITY_VIRTUALMODE_INDEXMAJOR == this.getVirtualMode()
        ) {
            return super.checkKeyState(objKey);
        }
        else
            return getSysRuntimeAdapterService().checkKeyReal(this, objKey);
    }

    /**
     * 数据源
     */
    @Override
    protected void onPushDataSource() {}

    /**
     * 数据源
     */
    @Override
    protected void onPollDataSource() {}

    /**
     * 执行预定义行为
     * @return
     */
    protected boolean isEnableExecutePredefinedAction() {
        return true;
    }

    /**
     * 判断实体是否包含该属性（优先按原codeName取，取不到时按codeName驼峰值取）
     * @param objEntity
     * @param iPSDEField
     * @return
     */
    @Override
    public boolean containsFieldValue(IEntityBase objEntity, IPSDEField iPSDEField) {
        boolean isContains = super.containsFieldValue(objEntity, iPSDEField);
        if (!isContains)
            isContains = getEntity(objEntity).contains(StringAdvUtils.camelcase(iPSDEField.getLowerCaseName()));
        return isContains;
    }

    /**
     * 执行实体行为：在执行标准行为前后进行对象转换 entity <-> entityDto
     * @param strActionName
     * @param iPSDEAction
     * @param args
     * @param actionData
     * @return
     * @throws Throwable
     */
    protected Object onExecuteAction(String strActionName, IPSDEAction iPSDEAction, Object[] args, Object actionData) throws Throwable {

        //判断输入是否为列表（LIST），如列表则循环处理
        if (args != null && args.length > 0 && args[0] instanceof List) {
            return super.onExecuteAction(strActionName,iPSDEAction,args,actionData);
        }

        ActionSession actionSession = ActionSessionManager.getCurrentSessionMust();
        ProceedingJoinPoint joinPoint = null;
        if (actionData != null && actionData instanceof ProceedingJoinPoint) {
            joinPoint = (ProceedingJoinPoint) actionData;
        }
        //实体行为映射
        IDEMapRuntime iDEMapRuntime = this.getDEMapRuntime(strActionName, iPSDEAction, PSModelEnums.DEMapObjectMapMode.DEFAULT.value);
        if (iDEMapRuntime != null) {
            log.debug(String.format("使用实体映射[%1$s]处理行为[%2$s]", iDEMapRuntime.getName(), (iPSDEAction != null ? iPSDEAction.getName() : strActionName)));
            return iDEMapRuntime.executeAction(strActionName, iPSDEAction, args, null);
        }
        //执行实体行为
        IEntityBase iEntityBase = null;
        Object arg0 = null;
        if (args != null && args.length > 0) {
            arg0 = args[0];
            if (arg0 instanceof IEntityBase) {
                iEntityBase = (IEntityBase) arg0;
            } else if (arg0 instanceof List) {
                if (joinPoint != null) {
                    return joinPoint.proceed();
                }
                throw new DataEntityRuntimeException(this, String.format("无法执行实体行为[%1$s]，传入列表参数无效", strActionName), Errors.INPUTERROR);
            }

        } else {
            if (joinPoint != null) {
                return joinPoint.proceed();
            }
            throw new DataEntityRuntimeException(this, String.format("无法执行实体行为[%1$s]，传入参数无效", strActionName), Errors.INPUTERROR);
        }
        IPSDEWF iPSDEWF = null;

        if (iPSDEWF == null) {
            iPSDEWF = this.calcCurrentPSDEWF(args[0]);
        }
        if (iPSDEWF == null) {
            iPSDEWF = this.getDefaultPSDEWF();
        }
        //进行工作流回调行为相关处理
        if (iEntityBase != null && iPSDEWF != null && strActionName.indexOf("wf") == 0) {
            onWFAction(strActionName, iEntityBase, iPSDEAction, iPSDEWF, joinPoint);
        }

        //计算动态实例实体运行时
        IDynaInstDataEntityRuntime iDynaInstDataEntityRuntime = null;
        IDynaInstRuntime iDynaInstRuntime = null;
        if (this.getDynaInstMode() != DynaInstModes.DISABLE) {
            String strDynainstid = getDynaInstId(arg0);
            if (StringUtils.hasLength(strDynainstid)) {
                iDynaInstRuntime = this.getSystemRuntime().getDynaInstRuntime(strDynainstid);
                // 设置当前会话的动态实例运行时
                ActionSessionManager.getCurrentSession().setDynaInstRuntime(iDynaInstRuntime);
                if (this.getDynaInstMode() == DynaInstModes.ENABLEINST) {
                    // 计算对应的实例
                    IEntityBase objEntity = null;
                    if (isGetDraftOrCreateAction(strActionName, iPSDEAction)) {
                        if (iEntityBase == null) {
                            throw new DataEntityRuntimeException(this, String.format("无法执行实体行为[%1$s]，传入参数无效", strActionName), Errors.INPUTERROR);
                        }
                        objEntity = iEntityBase;
                    } else {
                        objEntity = getLastEntity(arg0);
                    }
                    if (objEntity != null) {
                        Object objDataType = this.getFieldValue(objEntity, this.getDataTypePSDEField());
                        if (ObjectUtils.isEmpty(objDataType) && isGetDraftOrCreateAction(strActionName, iPSDEAction)) {
                            // 没有传入类型值，尝试计算
                            if (StringUtils.hasLength(this.getDynaInstTag()) && StringUtils.hasLength(actionSession.getUserContext().getDynainsttag()) && StringUtils.hasLength(actionSession.getUserContext().getDynainsttag2()) && this.getDynaInstTag().equals(actionSession.getUserContext().getDynainsttag())) {
                                objDataType = this.getSystemRuntime().convertValue(this.getDataTypePSDEField().getStdDataType(), actionSession.getUserContext().getDynainsttag2());
                                this.setFieldValue(objEntity, this.getDataTypePSDEField(), objDataType);
                            }
                        }
                        if (objDataType != null) {
                            String strChildDynaInstId = iDynaInstRuntime.getChildDynaInstId(this.getDynaInstTag(), objDataType.toString());
                            if (StringUtils.hasLength(strChildDynaInstId)) {
                                iDynaInstRuntime = this.getSystemRuntime().getDynaInstRuntime(strChildDynaInstId);
                                // 设置当前会话的子动态实例运行时
                                ActionSessionManager.getCurrentSession().setChildDynaInstRuntime(iDynaInstRuntime);
                                log.debug(String.format("实体[%1$s][%2$s][%3$s]计算实例=>[%4$s]", this.getName(), this.getDynaInstTag(), objDataType.toString(), strChildDynaInstId));
                            }
                        }
                    }
                }
                if (iDynaInstRuntime != null) {
                    iDynaInstDataEntityRuntime = iDynaInstRuntime.getDynaInstDataEntityRuntime(this.getId());
                    // 更替行为
                    iPSDEAction = iDynaInstDataEntityRuntime.getPSDEAction(strActionName);
                }
            }
        }

        if (isEnableInheritLogic()) {
            if (this.isInheritMajor()) {
                Object objKeyValue = null;
                if (iEntityBase != null) {
                    objKeyValue = this.getFieldValue(iEntityBase, this.getKeyPSDEField());
                } else {
                    objKeyValue = arg0;
                }

                // 判断是否为继承主实体，行为需要在子实体约束下
                if (this.isInheritMajorDataEntityCreate(strActionName, iPSDEAction)) {
                    if (actionSession.registerRecursion(RECURSION_INHERITACTION, this.getId(), objKeyValue, DEActions.CREATE)) {
                        throw new DataEntityRuntimeException(this, String.format("继承主实体不能独立建立数据"));
                    }
                } else if (this.isInheritMajorDataEntityUpdate(strActionName, iPSDEAction)) {
                    if (actionSession.registerRecursion(RECURSION_INHERITACTION, this.getId(), objKeyValue, DEActions.UPDATE)) {
                        throw new DataEntityRuntimeException(this, String.format("继承主实体不能独立更新数据"));
                    }
                } else if (this.isInheritMajorDataEntityRemove(strActionName, iPSDEAction)) {
                    if (actionSession.registerRecursion(RECURSION_INHERITACTION, this.getId(), objKeyValue, DEActions.REMOVE)) {
                        actionSession.unregisterRecursion(RECURSION_INHERITACTION, this.getId(), objKeyValue, DEActions.REMOVE);
                        // 中断当前操作
                        return inheritMinorDataEntityRemove(arg0, iPSDEAction, this.getPSDataEntity(), iDynaInstRuntime, args);
                    }
                }
            }
        }

        // 行为主状态控制检查
        if (iPSDEAction != null) {
            // 进行主状态控制
            checkDEMainState(arg0, iPSDEAction);
        }

        // 填充默认值
        if (iEntityBase != null && isEnableDefaultValueLogic()) {
            if (isFillEntityDefaultValues(strActionName, iPSDEAction)) {
                this.fillEntityDefaultValues(iEntityBase, strActionName, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, actionData);
            }

            if (isFillEntityFullInfo(strActionName, iPSDEAction)) {
                this.fillEntityFullInfo(iEntityBase, strActionName, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, actionData);
            }
        }

        // 判断是否进行实体主关系数据属性值处理，必须在检查值之前处理，关系中可能会定义映射聚合属性处理
        if (iEntityBase != null && isTranslateEntityNestedDERsBeforeProceed(strActionName, iPSDEAction)) {
            this.translateEntityNestedDERsBeforeProceed(iEntityBase, strActionName, iPSDEAction, this.getPSDataEntity(), iDynaInstRuntime, actionData);
        }

        // 判断是否做参数额外处理
        if (iEntityBase != null && isEnableActionParamLogic()) {
            if (iPSDEAction != null && iPSDEAction.isCustomParam()) {
                this.fillActionParams(iEntityBase, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, actionData);
            }
        }

        if (iPSDEAction != null && this.isEnableActionLogic(iPSDEAction, DEActionLogicAttachModes.PREPARE)) {// iPSDEAction.getPreparePSDEActionLogics()
            if (iEntityBase != null) {
                this.executeActionLogics(iEntityBase, iPSDEAction, DEActionLogicAttachModes.PREPARE, iDynaInstDataEntityRuntime, iDynaInstRuntime, actionData);
            } else {
                // 主键模式暂时不支持
            }
        }

        if (iEntityBase != null && isEnableDefaultValueLogic()) {
            if (isFillEntityDefaultValues(strActionName, iPSDEAction)) {
                this.fillEntitySequenceValues(iEntityBase, strActionName, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, actionData);
            }
        }

        // 主键
        if (iEntityBase != null && isEnableKeyValueLogic()) {
            if (isFillEntityKeyValue(strActionName, iPSDEAction)) {
                if (this.getUniTagPSDEField() != null && this.getUnionKeyValuePSDEFields() != null) {
                    // if (!this.containsFieldValue(iEntityBase,
                    // this.getUniTagPSDEField())) {
                    if (true) { // 直接更新
                        String strUniqueTag = this.getUniTagValue(iEntityBase, this.getUnionKeyValuePSDEFields());
                        if (StringUtils.hasLength(strUniqueTag)) {
                            if (this.checkKeyState(strUniqueTag) != CheckKeyStates.OK) {
                                throw new DataEntityRuntimeException(this, Errors.getErrorInfo(Errors.DUPLICATEDATA), Errors.DUPLICATEDATA);
                            } else {
                                this.setFieldValue(iEntityBase, this.getUniTagPSDEField(), strUniqueTag);
                            }
                        }
                    }
                }

                if (ObjectUtils.isEmpty(this.getFieldValue(iEntityBase, this.getKeyPSDEField()))) {
                    if (fillEntityKeyValue(iEntityBase)) {
                        Object objKeyValue = this.getFieldValue(iEntityBase, this.getKeyPSDEField());
                        if (!ObjectUtils.isEmpty(objKeyValue)) {
                            if (this.checkKeyState(objKeyValue) != CheckKeyStates.OK) {
                                throw new DataEntityRuntimeException(this, Errors.getErrorInfo(Errors.DUPLICATEKEY), Errors.DUPLICATEKEY);
                            }
                        }
                    }
                }
            }
        }

        // 进行删除前检查
        if (isCheckReferenceBeforeRemove(strActionName, iPSDEAction)) {
            this.checkReferenceBeforeRemove(arg0, strActionName, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, joinPoint);
        }

        // 准备上一次的数据
        // 如需要执行后构建父路径，准备处理前数据
        if (isPrepareLastBeforeProceed(strActionName, iPSDEAction)) {
            this.prepareLastBeforeProceed(arg0, strActionName, iPSDEAction, this.getPSDataEntity(), iDynaInstRuntime, actionData);
        }

        if (isEnableBuildParentPath() && isBuildParentPathBeforeProceed(strActionName, iPSDEAction)) {
            this.buildParentPathBeforeProceed(arg0, strActionName, iPSDEAction, this.getPSDataEntity(), iDynaInstRuntime, actionData);
        }

        // 进行操作之前值校验
        if (iEntityBase != null && isCheckEntityBeforeProceed(strActionName, iPSDEAction)) {
            this.checkEntityBeforeProceed(iEntityBase, strActionName, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, joinPoint);
            this.checkEntityNestedDERsBeforeProceed(iEntityBase, strActionName, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, joinPoint);
            if (this.isEnableDynaStorage()) {
                this.checkEntityDynaFieldsBeforeProceed(iEntityBase, strActionName, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, joinPoint);
            }
        }

        // 执行校验逻辑
        if (iPSDEAction != null && this.isEnableActionLogic(iPSDEAction, DEActionLogicAttachModes.CHECK)) {// iPSDEAction.getCheckPSDEActionLogics()
            // !=
            // null)
            // {
            if (iEntityBase != null) {
                this.executeActionLogics(iEntityBase, iPSDEAction, DEActionLogicAttachModes.CHECK, iDynaInstDataEntityRuntime, iDynaInstRuntime, joinPoint);
            } else {
                this.executeActionLogics(arg0, iPSDEAction, DEActionLogicAttachModes.CHECK, iDynaInstDataEntityRuntime, iDynaInstRuntime, joinPoint);
            }
        }

        // 执行审计前处理
        if (iEntityBase != null && this.isEnableDataAudit() && this.isAuditEntityBeforeProceed(strActionName, iPSDEAction)) {
            this.auditEntityBeforeProceed(iEntityBase, strActionName, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, joinPoint);
        }

        // 执行前逻辑
        if (iPSDEAction != null && this.isEnableActionLogic(iPSDEAction, DEActionLogicAttachModes.BEFORE)) {// iPSDEAction.getBeforePSDEActionLogics()
            // !=
            // null)
            // {
            if (iEntityBase != null) {
                this.executeActionLogics(iEntityBase, iPSDEAction, DEActionLogicAttachModes.BEFORE, iDynaInstDataEntityRuntime, iDynaInstRuntime, joinPoint);
            } else {
                this.executeActionLogics(arg0, iPSDEAction, DEActionLogicAttachModes.BEFORE, iDynaInstDataEntityRuntime, iDynaInstRuntime, joinPoint);
            }
        }

        // 进行值转换处理
        if (iEntityBase != null && this.isTranslateEntityBeforeProceed(strActionName, iPSDEAction)) {
            this.translateEntityBeforeProceed(iEntityBase, strActionName, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, joinPoint);
            if (this.isEnableDynaStorage()) {
                this.translateEntityDynaFieldsBeforeProceed(iEntityBase, strActionName, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, joinPoint);
            }
        }

        // 执行继承从实例关系
        if (iEntityBase != null && isEnableInheritLogic()) {
            if (isInheritMinor()) {
                // 判断当前行为是否为建立行为，如是需要先调用主实体
                if (this.isInheritMajorDataEntityCreate(strActionName, iPSDEAction)) {
                    inheritMajorDataEntityCreateOrUpdate(iEntityBase, true, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, joinPoint);
                } else if (this.isInheritMajorDataEntityUpdate(strActionName, iPSDEAction)) {
                    inheritMajorDataEntityCreateOrUpdate(iEntityBase, false, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, joinPoint);
                }
            }
        }

        // 重置引用数据的外键值
        if (isCheckReferenceBeforeRemove(strActionName, iPSDEAction)) {
            if (this.isEnableDynaStorage()) {
                this.removeEntityDynaFieldsBeforeRemove(arg0, strActionName, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, joinPoint);
            }
            this.resetReferenceBeforeRemove(arg0, strActionName, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, joinPoint);
            this.removeReferenceBeforeRemove(arg0, strActionName, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, joinPoint);
        }

        //执行标准行为前转换 entityDto -> entity
        if (arg0 != null && arg0 instanceof IEntityDTO && ((IEntityDTO) arg0).get(DELogicConstant.PARAM_DATAENTITY) != null) {
            cn.ibizlab.util.adapter.util.helper.CachedBeanCopier.copyEntityDto2Entity((IEntityDTO) arg0, (cn.ibizlab.util.domain.IEntity) ((IEntityDTO) arg0).get(DELogicConstant.PARAM_DATAENTITY));
        }

        Object objRet = null;
        IDEActionPluginRuntime iDEActionPluginRuntime = this.getDEActionPluginRuntime(iPSDEAction);
        if (joinPoint != null && iDEActionPluginRuntime == null) {
            // 标准执行
            objRet = joinPoint.proceed();
        } else {
            if (iDEActionPluginRuntime == null) {
                objRet = onExecuteActionReal(strActionName, iPSDEAction, args, actionData);
            } else {
                objRet = iDEActionPluginRuntime.execute(this.getDataEntityRuntimeContext(), iPSDEAction, args, actionData);
            }
        }

        //执行标准行为后转换 entity -> entityDto
        if (arg0 != null && arg0 instanceof IEntityDTO && ((IEntityDTO) arg0).get(DELogicConstant.PARAM_DATAENTITY) != null) {
            CachedBeanCopier.copyEntity2Dto((cn.ibizlab.util.domain.IEntity) ((IEntityDTO) arg0).get(DELogicConstant.PARAM_DATAENTITY), (IEntityDTO) arg0);
        }

        if (isEnableExecutePredefinedAction() && iDEActionPluginRuntime == null) {
            // 其它执行
            if (iPSDEWF != null && DEActions.WFSTART.equalsIgnoreCase(strActionName)) {
                IPSDEWF ActionPSDEWF = iPSDEWF;
                if (args.length >= 2 && (args[1] instanceof IPSDEWF)) {
                    ActionPSDEWF = (IPSDEWF) args[1];
                }
                this.onWFStart(arg0, iPSDEAction, ActionPSDEWF, iDynaInstRuntime, joinPoint);
            } else if (iPSDEWF != null && DEActions.WFCANCEL.equalsIgnoreCase(strActionName)) {
                IPSDEWF ActionPSDEWF = iPSDEWF;
                if (args.length >= 2 && (args[1] instanceof IPSDEWF)) {
                    iPSDEWF = (IPSDEWF) args[1];
                }
                this.onWFCancel(arg0, iPSDEAction, ActionPSDEWF, iDynaInstRuntime, joinPoint);
            } else if (iEntityBase != null && iPSDEAction != null) {
                if (DEActionTypes.DELOGIC.equals(iPSDEAction.getActionType())) {
                    IPSDELogicAction iPSDELogicAction = (IPSDELogicAction) iPSDEAction;
                    objRet = this.executeDELogic(iEntityBase, iPSDEAction, iPSDELogicAction.getPSDELogic(), iDynaInstRuntime, joinPoint);
                } else if (DEActionTypes.SCRIPT.equals(iPSDEAction.getActionType())) {
                    IPSDEScriptAction iPSDEScriptAction = (IPSDEScriptAction) iPSDEAction;
                    objRet = this.executeDEScriptLogic(iEntityBase, iPSDEScriptAction, null, iDynaInstRuntime, joinPoint);
                }
            }
        }

        // 判断是否进行实体主关系数据属性值处理
        if ((iEntityBase != null || objRet instanceof IEntityBase) && isTranslateEntityNestedDERsAfterProceed(strActionName, iPSDEAction)) {
            if (objRet instanceof IEntityBase) {
                this.translateEntityNestedDERsAfterProceed((IEntityBase) objRet, strActionName, iPSDEAction, getPSDataEntity(), iDynaInstRuntime, actionData);
            } else if (iEntityBase != null) {
                this.translateEntityNestedDERsAfterProceed(iEntityBase, strActionName, iPSDEAction, getPSDataEntity(), iDynaInstRuntime, actionData);
            }
        }

        // 更新进行值校验
        if (iEntityBase != null && isCheckEntityAfterProceed(strActionName, iPSDEAction)) {
            this.checkEntityAfterProceed(iEntityBase, strActionName, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, joinPoint);
        }

        // 构建父路径
        if (this.isEnableBuildParentPath() && this.isBuildParentPathAfterProceed(strActionName, iPSDEAction)) {
            this.buildParentPathAfterProceed(arg0, objRet, strActionName, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, joinPoint);
        }

        if (iEntityBase != null && this.isEnableEntityOnChangeLogic() && isExecuteEntityOnChangeLogic(strActionName, iPSDEAction)) {
            this.executeEntityOnChangeLogic(iEntityBase, strActionName, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, joinPoint);
        }

        if (this.isEnableDataAudit() && this.isAuditEntityAfterProceed(strActionName, iPSDEAction)) {
            this.auditEntityAfterProceed(arg0, objRet, strActionName, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, joinPoint);
        }

        // 登记或注销工作流工作
        if (iPSDEWF != null) {
            if (this.isWFRegisterEntityAfterProceed(strActionName, iPSDEAction)) {
                this.onWFRegister(arg0, iPSDEAction, iPSDEWF, iDynaInstRuntime, actionData);
            } else if (this.isWFUnregisterEntityAfterProceed(strActionName, iPSDEAction)) {
                this.onWFUnregister(arg0, iPSDEAction, iPSDEWF, iDynaInstRuntime, actionData);
            } else if (this.isFillWFTagAfterProceed(strActionName, iPSDEAction)) {
                this.onFillWFTag(arg0, iPSDEAction, iPSDEWF, iDynaInstRuntime, objRet);
            }
        }

        // 进行值转换处理
        if (this.isTranslateEntityAfterProceed(strActionName, iPSDEAction)) {
            if (this.isEnableDynaStorage()) {
                this.translateEntityDynaFieldsAfterProceed(arg0, objRet, strActionName, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, joinPoint);
            }
            this.translateEntityAfterProceed(arg0, objRet, strActionName, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, joinPoint);
        }

        // 进行索引数据处理
        if (this.isEnableIndexLogic()) {
            if (this.isIndexMinor()) {
                if (iEntityBase != null && isIndexMajorDataEntityCreate(strActionName, iPSDEAction)) {
                    indexMajorDataEntityCreateOrUpdate(iEntityBase, true, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, joinPoint);
                } else if (iEntityBase != null && isIndexMajorDataEntityUpdate(strActionName, iPSDEAction)) {
                    indexMajorDataEntityCreateOrUpdate(iEntityBase, false, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, joinPoint);
                } else if (isIndexMajorDataEntityRemove(strActionName, iPSDEAction)) {
                    indexMajorDataEntityRemove(arg0, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, joinPoint);
                }
            }
        }
        //
        // // 执行数据同步
        // if (this.isEnableDataSync()) {
        // int nDataSyncEvent = this.getDataSyncEvent(strActionName,
        // iPSDEAction);
        // if (nDataSyncEvent != DEDataSyncEvents.NONE) {
        // this.syncEntityAfterProceed(nDataSyncEvent, arg0, objRet,
        // strActionName, iPSDEAction, iPSDataEntity, iDynaInstRuntime,
        // actionData);
        // }
        // }

        // 放入后续异步处理队列
        if (this.isEnableDTSQueue() && this.getDefaultPSDEDTSQueue() != null) {
            if (isPushDTSQueueAfterProceed(strActionName, iPSDEAction)) {
                this.pushDTSQueueAfterProceed(arg0, objRet, strActionName, iPSDEAction, getPSDataEntity(), iDynaInstRuntime, actionData);
            }
        }

        if (isEnableInheritLogic()) {
            // 继承逻辑后续处理
            if (this.isInheritMajor()) {

            } else if (this.isInheritMinor()) {
                if (this.isInheritMajorDataEntityRemove(strActionName, iPSDEAction)) {
                    inheritMajorDataEntityRemove(arg0, iPSDEAction, (iDynaInstDataEntityRuntime == null) ? this.getPSDataEntity() : iDynaInstDataEntityRuntime.getPSDataEntity(), iDynaInstRuntime, joinPoint);
                }
            }
        }

        // 执行后逻辑
        if (iPSDEAction != null && this.isEnableActionLogic(iPSDEAction, DEActionLogicAttachModes.AFTER)) { // &&
            // iPSDEAction.getAfterPSDEActionLogics()
            // !=
            // null)
            // {
            if (objRet != null && objRet instanceof IEntityBase) {
                this.executeActionLogics((IEntityBase) objRet, iPSDEAction, DEActionLogicAttachModes.AFTER, iDynaInstDataEntityRuntime, iDynaInstRuntime, joinPoint);
            } else if (iEntityBase != null) {
                this.executeActionLogics(iEntityBase, iPSDEAction, DEActionLogicAttachModes.AFTER, iDynaInstDataEntityRuntime, iDynaInstRuntime, joinPoint);
            } else {
                this.executeActionLogics(arg0, iPSDEAction, DEActionLogicAttachModes.AFTER, iDynaInstDataEntityRuntime, iDynaInstRuntime, joinPoint);
            }
        }

        // 执行数据同步
        if (this.isEnableDataSync()) {
            int nDataSyncEvent = this.getDataSyncEvent(strActionName, iPSDEAction);
            if (nDataSyncEvent != DEDataSyncEvents.NONE) {
                this.syncEntityAfterProceed(nDataSyncEvent, arg0, objRet, strActionName, iPSDEAction, getPSDataEntity(), iDynaInstRuntime, actionData);
            }
        }

        //
        // // 执行数据通知
        // if (this.isEnableNotify()) {
        // this.notifyEntityAfterProceed(arg0, objRet, strActionName,
        // iPSDEAction, iPSDataEntity, iDynaInstRuntime, actionData);
        // }

        return objRet;
    }
}
